package de.gof.ppstool.xmlimport.ui;

import java.io.File;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;
import de.gof.ppstool.util.XMLException;

@ManagedBean(name = FileUploadBean.NAME)
@SessionScoped
public class FileUploadBean implements Serializable {
	private static final long serialVersionUID = -7304823100805667537L;
	public static final String NAME = "xmlim";
	@SuppressWarnings("unused")
	private String extension;
	@SuppressWarnings("unused")
	private String contentType;
	private byte[] bytes;
	private File file;
	@ManagedProperty(value = "#{" + XMLImporterBean.NAME + "}")
	private XMLImporterBean xb;

	public XMLImporterBean getXb() {
		return xb;
	}

	public void setXb(XMLImporterBean xb) {
		this.xb = xb;
	}

	public FileUploadBean() {
	}

	public void uploadListener(UploadEvent event) throws XMLException {
		UploadItem item = event.getUploadItem();
		contentType = item.getContentType();
		String origFilename = item.getFileName();
		int index = origFilename.lastIndexOf('.');
		extension = origFilename.substring(index + 1);
		if (!item.isTempFile()) {
			bytes = item.getData();
			System.out
					.println("Warning: XMLImporter won't be executed (the uploaditem is not set to be a tempfile (see entry in web.xml))");
		} else {
			file = item.getFile();
			if (xb != null)
				xb.readXML(file);
			else
				System.out.println("XMLImporter is null!");

		}

	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public byte[] getBytes() {
		return bytes;
	}

	public void setBytes(byte[] bytes) {
		this.bytes = bytes;
	}

}
